﻿<?php


class UserMapper extends DataMapperAbstract
{
	public function __construct(DataAdapter $db, GenericArray $scripts)
	{
		parent::__construct($db);
		$this->_scripts = $scripts;
	}
   
    // fetch domain object by ID
    public function find($token)
    {
        // get domain object from the database
        $this->query(sprintf($this->_scripts->user_find, $token));
        if ($row = $this->fetch())
            return new User($row);
		return NULL;
    }
    // fetch domain object by ID
    public function findByEmail($email)
    {
        // get domain object from the database
        $this->query(sprintf($this->_scripts->user_exists, $email));
        if ($row = $this->fetch())
            return new User($row);
		return NULL;
    }
	
    // save domain object
    public function save(GenericArray $user)
    {
		$this->query(sprintf($this->_scripts->user_insert, $user->full_name, $user->password, $user->email));
		return $this->findByEmail($user->email);
    }
   
    // update domain object
    public function update(GenericArray $user)
    {
        if ($user->token !== NULL)// update domain object
		{
			$query = sprintf($this->_scripts->user_update, $user->full_name, $user->password, $user->email, $user->token);
			$this->query($query);
			return $this->find($user->token);
		}
		return NULL;
    }
   
    // delete domain object
    public function delete(GenericArray $user)
    {
        if ($user->id !== NULL)
            $this->query(sprintf($this->_scripts->user_delete, $user->id));
    }
	
	public function connect(GenericArray $user)
	{
		// get domain object from the database
        $this->query(sprintf($this->_scripts->user_exists, $user->email));
        if ($row = $this->fetch())
		{
            $user2 = new User($row);
			if($user2->password == $user->password)
			{
				//generate a new token
				$user2->token = uniqid("U");
				$user2->last_session_date = date('Y-m-d H:i:s');
				$this->query(sprintf($this->_scripts->user_token, $user2->token, $user->last_session_date, $user2->id));
				return $user2;
			}
			return NULL;
		}
		return NULL;
	}
}
